package com.arthur.controller;

import com.arthur.bean.Cart;
import com.arthur.bean.Order;
import com.arthur.bean.PageBean;
import com.arthur.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class AddCartController {
    @Autowired
    @Qualifier("userService")
    private UserService userService;
    @RequestMapping("/AddCartController")
    @ResponseBody
    protected Map cartInfo(HttpServletRequest request, HttpServletResponse response)throws Exception{
        Map<String, Object> objectMap = new HashMap<>();
        response.setCharacterEncoding("UTF-8");
        String productname=request.getParameter("productname");
        String username=request.getParameter("username");
        Cart cart=new Cart();
        cart.setProductname(productname);
        cart.setUsername(username);

        int count = userService.addCartinfo(cart);
        if (count==1){
            objectMap.put("result","1");
        }
        return objectMap;
    }
    @RequestMapping("/cartInfoListController")
    @ResponseBody
    protected Map cartInfoList(HttpServletRequest request, HttpServletResponse response)throws Exception{
        Map<String, Object> objectMap = new HashMap<>();
        String username=request.getParameter("username");
        int pageno = 1;
        try {
            pageno = Integer.parseInt(request.getParameter("pageno"));

        } catch (Exception e) {
        }

        int totalRows = userService.obtainCartinfoRows();
        int maxpage = totalRows % PageBean.ROWS_PERPAGE == 0 ? totalRows / PageBean.ROWS_PERPAGE
                : (totalRows / PageBean.ROWS_PERPAGE + 1);

        if (pageno < 1) {
            pageno = 1;
        }

        if (pageno > maxpage) {
            pageno = maxpage;
        }
        List<Cart> cartinfoList = userService.fetchCartinfoListBypageno(pageno,username);
        response.setCharacterEncoding("UTF-8");
        if (cartinfoList == null || cartinfoList.size() < 1) {
            objectMap.put("result","0");
        } else {
            objectMap.put("prePage", pageno - 1);
            objectMap.put("nextPage", pageno + 1);
            objectMap.put("maxPage", maxpage);
            objectMap.put("cartinfoList", cartinfoList);
        }
        return objectMap;
    }
}
